<template>
  <div class="Tabs provider-main-new">
    <span v-if="serviceName === 'provider'" @click="Open" class="providerTag"
      >{{$t('serviceProvider.labelManage.tip1')}}</span
    >
    <!-- 账户分配信息S-->
    <div class="provider-top" ref="tableAccountTip">
      <div class="flex-x">
        <div class="icon iconfont icon-tip mar-r-8"></div>
        <div>{{$t('serviceProvider.accountTip.tip1')}}：
          <template v-if="allNum===0">{{$t('serviceProvider.accountTip.tip2')}}</template>
          <template v-else>{{ allNum }}{{$t('serviceProvider.accountTip.tip3')}}</template>
        </div>
        <div
          class="mar-l-4 cur-point c-primary"
          @click="openAccount">
          <span class="iconfont icon-edit-fill"></span>
        </div>
        <div class="provider-bar-line"></div>
        <div>{{$t('serviceProvider.accountTip.tip4', {assignedNum})}}</div>
        <div class="provider-bar-line"></div>
        <div>{{$t('serviceProvider.accountTip.tip5', { remainNum })}}</div>
        <div class="mar-l-8">
          <el-tooltip
            popper-class="provider-account-tip"
            effect="dark"
            placement="top"
            :content="$t('serviceProvider.accountTip.tip6')"
          >
            <span class="cur-point iconfont icon-question-circle"></span>
          </el-tooltip>
        </div>
      </div>
    </div>
    <!-- 账户分配信息E-->
    <el-tabs v-model="serviceName" class="main-tab" @tab-click="handleTabClick">
      <el-tab-pane :label="$t('common.base.serviceProvider')" name="provider">
        <span slot="label">{{ $t('common.base.serviceProvider') }}</span>
        <div
          :class="['service-list', { 'service-list-no': shareData.hideTopTip }]"
        >
          <provider-list
            ref="providerList"
            :other-class="['el-tabs__header']"
            :share-data="shareData"
            @refresh="refresh"
          ></provider-list>
        </div>
      </el-tab-pane>
    <el-tab-pane :label="$t('common.base.engineer')" name="engineer">
      <div :class="['service-list', {'service-list-no': shareData.hideTopTip}]">
          <engineer-list
            ref="engineerList"
            :other-class="['el-tabs__header']"
            :share-data="shareData"
            @refreshAccount="getTenantProviderAccountData"
          ></engineer-list>
        </div>
      </el-tab-pane>
    </el-tabs>
    <base-modal
      :title="$t('serviceProvider.labelManage.tip1')"
      :show.sync="isShow"
      width="500px"
      class="provider-account-set"
      :before-close="Close"
    >
      <div class="List">
        <draggable
          tag="div"
          v-bind="{ animation: 380 }"
          :list="list"
          handle=".handle"
          @update="update"
        >
          <div v-for="(item, index) in list" :key="item.id" class="TagItem">
            <div class="ItemInput">
              <el-input
                @change="SetName(item, index)"
                v-model.trim="item.labelName"
              />
            </div>
            <span class="iconfont icon-tuozhuaipaixu handle"></span>
            <span @click="Del(item, index)" class="iconfont icon-delete"></span>
          </div>
          <!-- 新建标签 -->
          <div v-if="list.length <= 100" class="TagItem">
            <div class="AddItem" @click="Add">
              <span class="iconfont icon-add2"></span>
              {{ $t('serviceProvider.labelManage.tip2') }}
            </div>
            <span></span>
            <span></span>
          </div>
        </draggable>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="plain-third" @click="Close">{{$t('common.base.cancel')}}</el-button>
        <el-button type="primary" @click="Close">{{$t('common.base.confirm')}}</el-button>
      </div>
    </base-modal>

    <!--设定账号-->
    <base-modal
      class="provider-account-set"
      :title="$t('serviceProvider.accountTip.tip7')"
      :show.sync="visible"
      width="480px"
    >
      <el-form ref="accountForm" :model="formAccount" :rules="rules">
        <el-form-item :label="$t('serviceProvider.accountTip.tip8')" prop="account">
          <el-input v-model.number="formAccount.account" ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="plain-third" @click="visible = false">{{$t('common.base.cancel')}}</el-button>
        <el-button type="primary" @click="validate" :disabled="pending">{{$t('common.base.confirm')}}</el-button>
      </div>
    </base-modal>
  </div>
</template>

<script>
import providerList from '../provider/providerList/ProviderList.vue';
import engineerList from '../engineer/engineerList/EngineerList';
import draggable from 'vuedraggable';
const MAX_COUNT = 9999999;
import {
  getProvideAllLabel,
  checkLabelNameRepeat,
  labelSave,
  deleteListByIds,
  getTenantProviderAccountData,
  saveTenantProviderAccount
} from '@src/api/serviceProviderApi';
export default {
  name: 'ProviderMain',
  components: {
    providerList,
    engineerList,
    draggable,
  },
  props: {
    shareData: {
      type: Object,
      default: () => ({}),
    },
    serviceTab: {
      type: String,
      default: 'provider',
    },
  },
  data() {
    return {
      serviceName: 'provider',
      isShow: false,
      list: [],
      visible: false,
      pending: false,
      formAccount: {
        account: ''
      },
      rules: {
        account: [
          { required: true, validator: this.validatorAccount, trigger: ['blur', 'input', 'change'] },
        ]
      },
      allNum:0, // 该租户的服务商总账号数
      assignedNum: 0, //已分配账号数
      remainNum: 0, // 剩余可分配账号数
      accountNum: 0, // 该租户总账号数
    };
  },
  watch: {
    serviceTab: {
      immediate: true,
      handler(val) {
        if (val) {
          this.serviceName = val;
        }
      },
    },
  },
  mounted() {
    // 获取该租户的服务商账号数据
    this.getTenantProviderAccountData();
    this.GetList();
  },
  methods: {
    // 校验账号
    validatorAccount(rule, value, cb) {
      if (value === '') {
        cb(new Error(this.$t('serviceProvider.accountTip.tip12')));
      }
      let reg = /^([1-9][0-9]*)$/
      if(!reg.test(value)) {
        cb(new Error(this.$t('serviceProvider.accountTip.tip9')));
      }
      if(value <= this.assignedNum) {
        cb(new Error(this.$t('serviceProvider.accountTip.tip10', {assignedNum: this.assignedNum})));
      }
      if(value > this.accountNum) {
        cb(new Error(this.$t('serviceProvider.accountTip.tip11', {accountNum: this.accountNum})));
      }

      return cb();
    },
    /*账号设定start*/
    openAccount() {
      this.$refs?.accountForm?.resetFields();
      this.formAccount.account = this.allNum
      this.visible = true;
    },
    validate() {
      this.$refs?.accountForm?.validate((valid) => {
        if(valid) {
          this.updateAccount();
        }
      })
    },
    async updateAccount() {
      try {
        let {success, message} = await saveTenantProviderAccount({account: this.formAccount.account});
        this.$message({
          message: success ? this.$t('serviceProvider.accountTip.tip13') : message,
          type: success ? 'success' : 'error'
        })
        this.pending = true;
        // 获取该租户的服务商账号数据
        this.getTenantProviderAccountData();
      } catch (e) {
        console.error(e)
      } finally {
        this.pending = false;
        this.visible = false;
      }
    },
    /*账号设定end*/
    // 获取租户的服务商账号
    async getTenantProviderAccountData() {
      try {
        let { success, result } = await getTenantProviderAccountData();
        if(success) {
          this.allNum = result?.allNum || 0;
          this.assignedNum = result?.assignedNum || 0;
          this.remainNum = result?.remainNum || 0;
          this.accountNum = result?.accountNum || 0;
        }
      } catch (e) {
        console.error(e)
      }
    },
    Open() {
      this.GetList();
      this.isShow = true;
    },
    Close() {
      this.GetList();
      this.isShow = false;
    },
    Add() {
      this.list.push({
        type: 0,
        createUserName: '',
      });
    },
    Del(item, index) {
      this.list.splice(index, 1);
      if (item?.id) {
        deleteListByIds([item.id])
        .then(res=>{
          if(res.status === 0){
            this.$message.success(this.$t('serviceProvider.labelManage.tip3'))
          }
        });
      }
    },
    update(value) {
      // 排序
      this.SetTag();
    },
    SetTag(addTag = false) {
      // 去除新增空值
      let saveParamList = this.list
        .filter(item => item.labelName)
        .map((item, index) => {
          let data = {
            name: item.labelName,
            priority: index + 1,
          };
          if (item?.id) {
            data.id = item?.id;
          }
          return data;
        });
      labelSave({
        objType: 1,
        saveParamList: saveParamList,
      }).then(res => {
        let succ = res?.succ
        if(addTag) {
          this.$message({
            type: succ ? 'success' : 'error',
            message: succ ? this.$t('serviceProvider.labelManage.tip4') : res?.message
          })
        }
        if(succ) this.GetList();
      });
    },
    SetName(item, index) {
      let data = {
        labelName: item.labelName,
        objType: 1,
      };
      if (item.id) {
        data.id = item.id;
      }
      // 重名校验
      checkLabelNameRepeat(data).then(res => {
        if (res.status === 0) {
          this.SetTag(true);
        } else {
          this.$message.error(this.$t('serviceProvider.labelManage.tip5'));
        }
      });
    },
    GetList() {
      getProvideAllLabel().then(res => {
        if (res.status === 0) {
          this.list = res.data.map(item => {
            item.type = 1;
            return item;
          });
        }
      });
    },
    handleTabClick(type) {
      let name = type?.name;
      switch (name) {
        case 'provider':
          this.$refs.providerList?.refreshProvider(); // 服务商列表;
          break;
        case 'engineer':
          this.$refs.engineerList?.refreshEngineer(); // 工程师列表
          break;
        default:
          return;
      }
    },
    refresh() {
      this.$emit('refresh');
    },
  },
};
</script>

<style scoped lang="scss">
.List {
  overflow-y: auto;
}
.AddItem {
  height: 32px;
  background: #f5f8fa;
  border: 1px solid #cbd6e2;
  flex: 1 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: 400;
  color: #595959;
  border-radius: 4px;
  cursor: pointer;
}
.Tabs {
  position: relative;
}
.TagItem {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  span {
    flex: 0 1 40px;
    display: flex;
    justify-content: center;
    cursor: pointer;
  }
}
.ItemInput {
  flex: 1 1 auto;
}
.providerTag {
  position: absolute;
  font-size: 14px;
  font-weight: 400;
  color: $color-primary-light-5;
  top: 70px;
  right: 30px;
  cursor: pointer;
  z-index: 100;
}
::-webkit-scrollbar {
  width: 5px;
}
.provider-main-new {
  background: white;
  padding-top: 12px;
  margin-right: 12px;
  border-radius: 4px;
}
.provider-top {
  height: 40px;
  background: $color-primary-light-1;
  border-radius: 4px;
  border: 1px solid $color-primary-light-3;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 0 12px 8px;
  padding: 0 16px;
  font-size: 14px;
  font-weight: 400;
  color: $text-color-regular;
  .icon-tip, .icon-edit-fill{
    color: $color-primary;
  }
  .provider-bar-line {
    background-color: #a8a8a8;
    height: 14px;
    width: 1px;
    margin: 4px 12px;
  }
}
.main-tab {
  background: white;
  border-radius: 4px;
  .service-list {
    height: calc(100vh - 178px);
  }
  .service-list-no {
    height: calc(100vh - 130px);
  }
  ::v-deep .el-tabs__header {
    margin-left: 16px;
    margin-bottom: 0;
  }
}
.provider-account-set {
  ::v-deep .base-modal-body {
    padding: 24px;
  }
}
</style>
<style lang="scss">
.provider-account-tip {
  width: 230px;
}
</style>
